package com.hzit.task.job.alipay;

import com.alibaba.fastjson.JSONArray;
import com.google.gson.JsonObject;
import com.hzit.paycommon.paycommonapi.aliapy.AliapyTradeQueryReq;
import com.hzit.paycommon.paycommonapi.aliapy.resp.AlipayTradeQueryRespData;
import com.hzit.paycommon.paycommonapi.resp.RespVo;
import com.hzit.task.iclient.IPayWebClient;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 定时任务：每隔5分钟，就去支付宝查询一下结果。
 */
@Component
public class AlipayTradeQueryTask {

    private static Logger logger = LoggerFactory.getLogger(AlipayTradeQueryTask.class);

    @Autowired
    private IPayWebClient iPayWebClient;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("alipayTradeQueryTask")
    public ReturnT<String> alipayTradeQueryTask(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, Hello World.");

        //1.取出支付流水表中的 支付中的数据。

        RespVo respVo = iPayWebClient.queryTrdeing("alipay");

        JSONArray jsonArray = (JSONArray)respVo.getData();

        if (jsonArray == null){
            XxlJobLogger.log("没有数据.");
            return ReturnT.SUCCESS;
        }

        for(int i =0; i<jsonArray.size();i++){
           JsonObject jsonObject = (JsonObject)jsonArray.get(i);

           //2.调用支付前置服务中，支付宝交易查询接口  fegn 调用pay-web，中支付中状态的流水。
            AliapyTradeQueryReq tradeQueryReq = new AliapyTradeQueryReq();

            tradeQueryReq.setOutTradeNo(jsonObject.get("outTradeNo").toString());
            tradeQueryReq.setOutTradeNo(jsonObject.get("tradeNo").toString());
            RespVo<AlipayTradeQueryRespData> respDataRespVo  = restTemplate.postForObject("http://127.0.0.1:8081/alipay/tradeQuery",tradeQueryReq,RespVo.class);


            //3.解析返回的结果，更新支付流水。        fegin  调用 pay-web 更新流水接口
            AlipayTradeQueryRespData respData = respDataRespVo.getData();

            //4.通知下业务系统. TODO

        }

        return ReturnT.SUCCESS;
    }

}
